<template>
  <div>
    <!-- 标题区域 -->
    <van-nav-bar :title="cmtObj.reply_count + '条回复'" class="topheader" />
    <!-- 被回复的这个人的评论和基本信息 -->
    <div class="cmt-item">
      <!-- 头部区域 -->
      <div class="cmt-header">
        <!-- 头部左侧 -->
        <div class="cmt-header-left">
          <img :src="cmtObj.aut_photo" alt="" class="avatar" />
          <span class="uname">{{ cmtObj.aut_name }}</span>
          <van-tag type="primary" style="margin-left: 0.266667rem"
            >楼主</van-tag
          >
        </div>
        <!-- 头部右侧 -->
        <div class="cmt-header-right">
          <van-icon
            name="good-job"
            size="0.426667rem"
            color="red"
            v-if="cmtObj.is_liking"
            @click="likeFn(false, cmtObj)"
          />

          <van-icon
            name="good-job-o"
            size="0.426667rem"
            color="gray"
            v-else
            @click="likeFn(true, cmtObj)"
          />
          <span class="commentDZcount">{{ cmtObj.like_count }}</span>
        </div>
      </div>
      <!-- 主体区域 -->
      <div class="cmt-body">
        {{ cmtObj.content }}
      </div>
      <!-- 尾部区域 -->
      <div class="cmt-footer">{{ formatDate(cmtObj.pubdate) }}</div>
    </div>
    <!-- 分割线 -->
    <van-divider></van-divider>
    <!-- 回复这个人的评论的所有回复列表 -->
    <div class="replylist">
      <h1 class="allreply" id="allreply">全部回复</h1>

      <!-- 评论列表 -->
      <div
        v-if="commentreplylist.length > 0"
        :class="inputflag ? 'art-cmt-container-1' : 'art-cmt-container-2'"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          :immediate-check="false"
          offset="10"
          @load="onLoad"
        >
          <!-- 评论的 Item 项 -->
          <div
            class="cmt-item nono"
            v-for="(obj, index) in commentreplylist"
            :key="index"
          >
            <!-- 头部区域 -->
            <div class="cmt-header">
              <!-- 头部左侧 -->
              <div class="cmt-header-left">
                <img :src="obj.aut_photo" alt="" class="avatar" />
                <span class="uname">{{ obj.aut_name }}</span>
                <van-tag
                  type="primary"
                  style="margin-left: 0.266667rem"
                  v-show="obj.aut_name === cmtObj.aut_name"
                  >楼主</van-tag
                >
              </div>
              <!-- 头部右侧 -->
              <div class="cmt-header-right">
                <van-icon
                  name="good-job"
                  size="0.426667rem"
                  color="red"
                  v-if="obj.is_liking"
                  @click="likeFn(false, obj.com_id)"
                />

                <van-icon
                  name="good-job-o"
                  size="0.426667rem"
                  color="gray"
                  v-else
                  @click="likeFn(true, obj.com_id)"
                />
                <span class="commentDZcount">{{ obj.like_count }}</span>
              </div>
            </div>
            <!-- 主体区域 -->
            <div class="cmt-body">
              <div class="replybox">
                <span class="berepliedto" v-if="obj.replymessage !== ''">{{
                  obj.replymessage
                }}</span>
              </div>
              <div class="replycontent">{{ obj.content }}</div>
            </div>
            <!-- 尾部区域 -->
            <div class="cmt-footer dates">
              <span class="reply" @click="replythisFn(obj)"
                >回复<van-icon name="arrow" size="0.32rem"
              /></span>
              {{ formatDate(obj.pubdate) }}
            </div>
          </div>
        </van-list>
      </div>
      <!-- 没有评论时 -->
      <div class="van-empty" v-else>
        <img src="@/assets/shafa.jpeg" alt="" />
      </div>
    </div>
    <!-- 底部添加评论区域 - 1 -->
    <div class="add-cmt-box van-hairline--top" v-if="inputflag">
      <div class="ipt-cmt-div" @click="inputshow">发表评论</div>
      <div class="icon-box">
        <van-icon
          name="good-job"
          size="0.53333334rem"
          color="red"
          v-if="cmtObj.is_liking"
          @click="likeFn(false, cmtObj)"
        />

        <van-icon
          name="good-job-o"
          size="0.53333334rem"
          color="gray"
          v-else
          @click="likeFn(true, cmtObj)"
        />
        <van-icon name="share-o" size="0.53333334rem" />
      </div>
    </div>
    <!-- 底部添加评论区域 - 2 -->
    <div class="cmt-box van-hairline--top" v-else>
      <textarea
        id="demo"
        :placeholder="textval"
        @blur="blurFn"
        v-focus
        v-model.trim="addcommentObj.content"
      ></textarea>
      <van-button
        type="default"
        :disabled="addcommentObj.content === ''"
        @click="FBcomment"
        >发布</van-button
      >
    </div>
  </div>
</template>

<script>
import { timeAgo } from '@/utils/date.js'
import { getStorage, setStorage } from '@/utils/storage.js'
import {
  getAllComment,
  LikeComment,
  UnLikeComment,
  addComment,
} from '@/api/comments/index.js'
export default {
  name: 'ReplyList',
  props: {
    cmtObj: {
      type: Object,
    },
  },
  data() {
    return {
      CommentReplyObj: {
        type: 'c', // 评论类型, 只能是'a'或'c', 'a'代表对文章的评论列表, 'c'代表对评论的回复列表
        source: '', // 文章id或评论id, 如果type为'a'这里传递文章id, 如果type为'c'这里传评论id
        offset: null, // 偏移量id(评论id), 值为评论id, 偏移量, 表示告诉后台从此id往后返回数据给前端, 做加载更多效果 axios发现值为null会自动忽略此参数
        limit: 10, // 获取评论数量, 不传, 默认后台返回10条
      },
      ReplyObj: {
        type: 'c', // 评论类型, 只能是'a'或'c', 'a'代表对文章的评论列表, 'c'代表对评论的回复列表
        source: '', // 文章id或评论id, 如果type为'a'这里传递文章id, 如果type为'c'这里传评论id
        offset: null, // 偏移量id(评论id), 值为评论id, 偏移量, 表示告诉后台从此id往后返回数据给前端, 做加载更多效果 axios发现值为null会自动忽略此参数
        limit: 10, // 获取评论数量, 不传, 默认后台返回10条
      },
      commentreplylist: [], // 该评论的所有回复列表
      inputflag: true, // 是否展示底部评论区域1 true展示 false展示底部评论区域2
      addcommentObj: {
        target: 0, // 评论的目标id id可以为文章id或评论的id 默认为楼主的评论id
        content: '', // 发表评论的内容
        art_id: this.$route.query.articleId, // 对评论回复需要此参数值, 代表所属文章id, 对文章评论无需此参数
      },
      textval: '', // 输入框站位提示文字 默认为楼主的基本信息
      loading: false, // 上拉加载更多数据的状态
      finished: false, // 上拉加载 是否加载完毕
      fbflag: false, // 为false则是回复楼主的 为true则是回复评论的
      replyArray: JSON.parse(getStorage('replyData')) || [],
    }
  },
  methods: {
    // 获取该评论的所有回复列表
    async getallcommentreply() {
      const { data: res } = await getAllComment(this.CommentReplyObj)
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '获取数据失败' })
      }
      console.log('该评论的回复列表数据:', res)
      this.loading = false
      if (res.data.results.length === 0) {
        let count = 0
        console.log(this.commentreplylist.length)
        if (this.commentreplylist.length < 5) {
          count = 100
        } else if (
          this.commentreplylist.length >= 5 &&
          this.commentreplylist.length < 10
        ) {
          count = 700
        } else {
          count = 1000
        }
        setTimeout(() => {
          this.finished = true
          return false
        }, count)
      }
      this.commentreplylist = [...this.commentreplylist, ...res.data.results]
      this.commentreplylist = this.commentreplylist.map((x) => {
        return { ...x, replymessage: '' }
      })
      this.CommentReplyObj.offset = res.data.last_id // 偏移量 用来请求下一页数据
      this.getallreply()
    },
    // 获取该回复的所有回复
    getallreply() {
      this.commentreplylist.forEach((x) => {
        if (x.reply_count > 0) {
          this.ReplyObj.source = x.com_id
          this.getallreplyFn()
        }
      })
    },
    async getallreplyFn() {
      const { data: res } = await getAllComment(this.ReplyObj)
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '获取数据失败' })
      }
      this.commentreplylist = [...this.commentreplylist, ...res.data.results]
      this.Deduplication()
    },
    // 数组去重
    Deduplication() {
      const newarray = []
      this.commentreplylist.forEach((x) => {
        const findResult = newarray.some((y) => y.com_id === x.com_id)
        if (!findResult) newarray.push(x)
      })
      this.commentreplylist = newarray
      this.getreplycontent()
    },
    // 上拉加载更多
    onLoad() {
      if (this.commentreplylist.length > 0) {
        this.getallcommentreply()
      }
    },
    // 获取被回复的评论的内容
    getreplycontent() {
      this.replyArray.forEach((x) => {
        const findResult1 = this.commentreplylist.find(
          (y) => y.com_id === x.com_id
        )
        const findResult2 = this.commentreplylist.find(
          (z) => z.com_id === x.target
        )
        // console.log(findResult1)
        // console.log(findResult2)
        if (findResult1 && findResult2) {
          return (findResult1.replymessage =
            '@' + findResult2.aut_name + ': ' + findResult2.content)
        }
      })
    },
    // 点击了点赞
    async likeFn(flag, kind) {
      const lx = typeof kind
      if (lx === 'object') {
        // 点在了楼主的点赞按钮上
        this.likeAPI(flag, kind, kind.com_id)
      } else {
        // 点在了回复的评论的点赞按钮上
        const findResult = this.commentreplylist.find((x) => x.com_id === kind)
        this.likeAPI(flag, findResult, kind)
      }
    },
    // 调用点赞/取消点赞接口
    async likeAPI(flag, findResult, id) {
      // console.log(flag, findResult, id)
      if (flag) {
        // 点击了点赞按钮 调用点赞评论接口 展示已点赞按钮 点赞数量加1
        const { data: res } = await LikeComment(id)
        if (res.message !== 'OK') {
          return this.$notify({ type: 'danger', message: '操作失败' })
        }
        findResult.is_liking = true
        findResult.like_count++
      } else {
        // 再次点击点赞按钮 调用取消点赞评论接口 展示点赞按钮点赞数量减1
        const { data: res } = await UnLikeComment(id)
        findResult.is_liking = false
        findResult.like_count--
        console.log(res)
      }
    },
    // 点击了发表评论
    inputshow() {
      this.inputflag = false
      this.fbflag = false
      this.addcommentObj.target = this.cmtObj.com_id
      this.textval = '回复' + this.cmtObj.aut_name + ':' + this.cmtObj.content
    },
    // 输入框失焦事件
    blurFn() {
      setTimeout(() => {
        this.inputflag = true
        this.addcommentObj.content = ''
      }, 0)
    },
    // 输入框内容输完--->发布文章评论
    // 发现bug-->当点击发布 输入框失焦 然后就隐藏了该输入框和发布按钮 也就没有了发布按钮的点击事件
    // 解决--->让输入框失焦事件延时触发
    async FBcomment() {
      const { data: res } = await addComment(this.addcommentObj)
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '操作失败' })
      }
      // console.log(res)
      if (this.fbflag) {
        this.replyArray.push({
          target: res.data.target,
          com_id: res.data.com_id,
        })
        setStorage('replyData', JSON.stringify(this.replyArray))
        this.textval = this.textval.replace('回复', '@')
        this.commentreplylist.unshift({
          ...res.data.new_obj,
          replymessage: this.textval,
        })
      } else {
        this.commentreplylist.unshift({ ...res.data.new_obj, replymessage: '' })
      }
      this.$toast({ type: 'success', message: '发布成功', duration: 500 })
      this.$emit('addreply', this.cmtObj.com_id)
    },
    replythisFn(obj) {
      if (this.inputflag === false) {
        return false
      }
      console.log(obj)
      this.inputflag = false
      this.fbflag = true
      this.addcommentObj.target = obj.com_id
      this.textval = '回复' + obj.aut_name + ':' + obj.content
    },
    // 格式化时间
    formatDate(str) {
      return timeAgo(str)
    },
  },
  watch: {
    // 监听父组件传过来的对象的com_id
    'cmtObj.com_id': {
      handler(newval, oldval) {
        // console.log(newval, oldval)
        this.CommentReplyObj.source = newval
        this.CommentReplyObj.offset = null
        this.commentreplylist = []
        this.finished = false
        this.getallcommentreply()
      },
      immediate: true,
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .van-nav-bar {
  background-color: #fff;
}
.cmt-item {
  padding: 15px;
  .cmt-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .cmt-header-left {
      display: flex;
      align-items: center;
      .avatar {
        width: 40px;
        height: 40px;
        background-color: #f8f8f8;
        border-radius: 50%;
        margin-right: 15px;
      }
      .uname {
        font-size: 12px;
      }
    }
  }
  .cmt-body {
    font-size: 14px;
    line-height: 28px;
    text-indent: 4em;
    margin-top: 6px;
    word-break: break-all;
  }
  .cmt-footer {
    font-size: 12px;
    color: gray;
    margin-top: 10px;
    text-indent: 55px;
  }
}
//点赞数量文字
.commentDZcount {
  color: gray;
  font-size: 16px;
  margin-left: 10px;
}
//回复
.reply {
  width: 60px;
  height: 25px;
  background: #f7f8fa;
  border-radius: 12px;
  display: inline-block;
  line-height: 25px;
  text-align: center;
  font-size: 12px;
  text-indent: 0;
  margin-right: 5px;
}
.replylist {
  padding: 0 15px;
  .allreply {
    font-size: 16px;
  }
}
.nono {
  padding: 15px 0 0 0 !important;
}
.dates {
  text-indent: 4em !important;
}
/*美化 - 文章详情 - 底部的评论页面 */
// 外层容器
.art-cmt-container-1 {
  padding-bottom: 46px;
}
.art-cmt-container-2 {
  padding-bottom: 80px;
}
// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 20%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  textarea {
    flex: 1;
    height: 66%;
    border: 1px solid #efefef;
    background-color: #f8f8f8;
    resize: none;
    border-radius: 6px;
    padding: 5px;
  }
  .van-button {
    height: 100%;
    border: none;
  }
}
.berepliedto {
  padding: 3px 6px;
  background-color: #f8f8f8;
}
.replycontent {
  padding: 0 0 0 4em;
  text-indent: 0 !important;
}
.replybox {
  padding: 0 0 0 4em;

  text-indent: 0 !important;
}
</style>
